package com.my.redisson.controller;

import com.my.redisson.delayqueue.DelayQueueProvider;
import com.my.redisson.domain.DelayEvent;
import com.my.redisson.domain.dto.req.AddDelayEventReq;
import com.my.redisson.domain.dto.req.RemoveDelayEventReq;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collection;
import java.util.UUID;

@RestController
public class DelayQueueController {

    @Autowired
    private DelayQueueProvider delayQueueProvider;

    @PostMapping("/addDelayEvent")
    public String addDelayEvent(@Valid AddDelayEventReq req) {
        if (req.getBizId() == null) {
            req.setBizId(uuid());
        }
        DelayEvent event = new DelayEvent();
        BeanUtils.copyProperties(req, event);
        event.setOnTime(System.currentTimeMillis() + event.getDelayTime());
        delayQueueProvider.addDelayEvent(event);
        return event.getBizId();
    }

    @PostMapping("/removeDelayEvent")
    public String removeDelayEvent(@Valid RemoveDelayEventReq req) {
        DelayEvent event = new DelayEvent();
        BeanUtils.copyProperties(req, event);
        delayQueueProvider.removeDelayEvent(event);
        return event.getBizId();
    }

    private String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @GetMapping("/delayEventList")
    public Collection<DelayEvent> getDelayEventList() {
        return delayQueueProvider.getDelayEventList();
    }
}
